﻿using Bilibili.Common.Log;
using System;
using System.IO;
using System.Text;
using Xml2Ass;

namespace Bilibili.Common.Danmaku
{
    public sealed class AssConverter
    {
        static AssConverter()
        {
            string location = Path.Combine(Extension.GetRoot(true), "Ass");
            Directory.CreateDirectory(location);
        }
        public static string ConvertTo(string danmakusXml, (double Height, double Width) videoSize, string id, int fontSize = 64)
        {
            string location = Path.Combine(Extension.GetRoot(true), "Ass", $"{id}.ass");
            var assContent = DanmakuConverter.ConvertToAss(danmakusXml, Convert.ToInt32(videoSize.Width), Convert.ToInt32(videoSize.Height), "Semi", fontSize);
            return Save(assContent, location) ? location : string.Empty;
        }
        public static string ConvertTo(FileInfo danmakusFile, (double Height, double Width) videoSize, string id, int fontSize = 64)
        {
            string location = Path.Combine(Extension.GetRoot(true), "Ass", $"{id}.ass");
            var assContent = DanmakuConverter.ConvertToAss(danmakusFile, Convert.ToInt32(videoSize.Width), Convert.ToInt32(videoSize.Height), "Semi", fontSize);
            return Save(assContent, location) ? location : string.Empty;
        }
        public static void Clear()
        {
            var files = Directory.GetFiles(Path.Combine(Extension.GetRoot(true), "Ass"));
            if (files != null)
            {
                foreach (var file in files)
                    File.Delete(file);
            }
        }
        private static bool Save(string content, string location)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(location);
                if (fileInfo.Exists)
                    fileInfo.Delete();
                using var fs = fileInfo.Create();
                var bytes = Encoding.UTF8.GetBytes(content);
                fs.Write(bytes, 0, bytes.Length);
                return true;
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("Save", ex);
            }
            return false;
        }
    }
}